package com.albert.core.service.impl;

import com.albert.core.listener.ExcelDictListener;
import com.albert.core.mapper.DictMapper;
import com.albert.core.pojo.dto.ExcelDictDto;
import com.albert.core.pojo.entity.Dict;
import com.albert.core.service.DictService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Hikari
 * @since 2024-07-21
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    private DictMapper dictMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDto.class,new ExcelDictListener(baseMapper)).sheet().doRead();
        log.info("业务层导入成功");
    }

    @Override
    public List<ExcelDictDto> listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        //创建ExcelDictDTO列表，将Dict列表转换成ExcelDictDTO列表
        ArrayList<ExcelDictDto> dictDtoList = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            ExcelDictDto excelDictDTO = new ExcelDictDto();
            BeanUtils.copyProperties(dict, excelDictDTO);
            dictDtoList.add(excelDictDTO);
        });
        return dictDtoList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        //首先查询缓存中是否存在
        try {
            List<Dict> list = (List<Dict>)redisTemplate.opsForValue().get("core:dictList:" + parentId);
            if(list.size()>0){
                return list;
            }
        } catch (Exception e) {
            log.info("redis出现异常"+e.getStackTrace());
        }
        log.info("开始从数据库获取redis");
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        dictList.forEach(dict -> {
            //如果有子节点，则是非叶子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        });
        try {
            //数据存入redis
            redisTemplate.opsForValue().set("core:dictList:" + parentId,dictList,60, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.info("redis存数据异常"+e.getStackTrace());
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return this.listByParentId(dict.getId());
    }


    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>().eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if(count.intValue() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict parentDict = baseMapper.selectOne(wrapper);
        if(parentDict==null){
            return "";
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentDict.getId()).eq("value",value);
        Dict dict = baseMapper.selectOne(wrapper);
        if(dict==null){
            return "";
        }
        return dict.getName();
    }
}
